const util = require('../../../../utils/util.js');
const cryptoJs = require('../../../../utils/cryptoJs.js');
const keyService = require('../../../../data/keyService.js');
const globalData = getApp().globalData;

Page({
  data: {
    isOldPassword: false,
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  },
  //输入框
  inputBlurBind: function(event) {
    const inputValue = event.detail.value;
    const inputName = event.currentTarget.dataset.name;

    this.data[inputName] = inputValue;
  },
  //保存
  passwordSaveBind: function() {
    const isOldPassword = this.data.isOldPassword;
    const oldPassword = this.data.oldPassword;
    const newPassword = this.data.newPassword;
    const confirmPassword = this.data.confirmPassword;

    if (isOldPassword) {
      if (oldPassword.trim() == '') {
        util.showToast('请输入原密码！');
        return;
      }
      const enPassword = globalData.userInfo.enPassword;
      if (enPassword != cryptoJs.MD5Encrypt(oldPassword)) {
        util.showToast('原密码输入不正确！');
        return;
      }
    }

    if (newPassword.trim() == '') {
      util.showToast('请输入新密码！');
      return;
    }
    if (confirmPassword.trim() == '' || newPassword != confirmPassword) {
      util.showToast('两次输入密码不一致！');
      return;
    }

    const oldEnPassword = globalData.userInfo.enPassword;
    const nowTime = new Date().getTime();

    globalData.userInfo.enPassword = cryptoJs.MD5Encrypt(newPassword);
    globalData.userInfo.time = nowTime;
    globalData.password = newPassword;
    if (globalData.authenPassword != '') { //处理指纹密码
      globalData.authenPassword = newPassword;
    }
    globalData.time = nowTime;

    util.setStorageData(globalData.localConfigName, globalData);
    if (!isOldPassword) {
      util.navigateBack();
      util.showToast('密码修改成功！');
      return;
    }
    //有旧密码,并且有正式数据
    let localJsonData = util.getStorageData(globalData.localJsonName);
    //原密码解密
    localJsonData = keyService.deJsonData(localJsonData, oldPassword);

    localJsonData.userInfo.enPassword = globalData.userInfo.enPassword;
    localJsonData.userInfo.time = nowTime;
    localJsonData.time = nowTime;
    //新密码加密
    localJsonData = keyService.enJsonData(localJsonData, newPassword);
    util.setStorageData(globalData.localJsonName, localJsonData);
    if (!localJsonData.userInfo.isCloudSyn) {
      util.navigateBack();
      util.showToast('密码修改成功！');
      return;
    }
    util.setCloudDbData(globalData.cloudJsonName, localJsonData).then(res => {
      util.navigateBack();
      util.showToast('密码修改成功！');
    }).catch(err => {
      console.error(err);
      util.showToast('同步失败！');
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const enPassword = globalData.userInfo.enPassword;
    if (enPassword != undefined && enPassword != '') {
      this.setData({
        isOldPassword: true
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  }
})